const audio = wx.createInnerAudioContext(); 
audio.src = 'https://7072-project-1gxmyb055bb0207d-1329171303.tcb.qcloud.la/audio/%E8%83%8C%E6%99%AF%E9%9F%B3%E4%B9%90.mp3?sign=f37293c51ba9f4217df17e7f6b70f67a&t=1727519021'; 

audio.loop = true;

const correct_audio = wx.createInnerAudioContext();
correct_audio.src = 'https://7072-project-1gxmyb055bb0207d-1329171303.tcb.qcloud.la/audio/%E7%AD%94%E5%AF%B9%E4%BA%86%E9%9F%B3%E6%95%88.mp3?sign=0b505ab5fea0f9c7e723b4e4b766d774&t=1727683665';

const incorrect_audio = wx.createInnerAudioContext();
incorrect_audio.src = 'https://7072-project-1gxmyb055bb0207d-1329171303.tcb.qcloud.la/audio/%E7%AD%94%E9%94%99%E4%BA%86%E9%9F%B3%E6%95%88.MP3?sign=ece566cafe698ae268d35335e5affa19&t=1727684437';

Page({
  data: {
    questions: [], // 存储随机选择的题目
    currentQuestionIndex: 0, // 当前题目索引
    selectedOption: '', // 当前选中的选项
    isCorrect: false, // 答案是否正确
    totalQuestions: 10, // 总题目数量（固定为 10 道）
    score: 0, // 当前分数
    isPlaying: false, // 音乐是否在播放的状态
    rotation: 0,
    quizId: '', // 存储传入的 ID
    answers: [], // 存储所有答题记录
    quizCompleted: false,
    button_status:false,
  },

  onLoad: function (options) {
    const id = options._id; // 获取传递过来的 ID
    if (id) {
      console.log('接收到的ID:', id); // 输出 ID，帮助调试
      this.setData({ quizId: id }); // 存储传入的 ID
    } else {
      console.error('未接收到ID');
    }
    this.getRandomQuestions(); // 获取随机题目
    this.toggleMusic(); 
  },

  look_options:function(){
    wx.navigateTo({
      url: `../answer_record/answer_record?_id=${this.data.quizId}`,
    })
  },

  // 获取10道随机题目
  getRandomQuestions: function () {
    const db = wx.cloud.database();
    db.collection('cms-questions').aggregate().sample({ size: 10 }).end({
      success: res => {
        if (res.list.length > 0) {
          this.setData({
            questions: res.list, // 存储随机选择的题目
            totalQuestions: res.list.length // 更新总题目数量
          });
          this.getQuestion(0); // 加载第一题
        }
      },
      fail: err => {
        console.error('获取随机题目失败', err);
      }
    });
  },

  // 根据索引获取题目
  getQuestion: function (index) {
    if (this.data.quizCompleted) return;
    const question = this.data.questions[index];
    if (question) {
      this.setData({
        question: question,
        selectedOption: '', // 重置选项
        isCorrect: false // 重置答案状态
      });
    }
  },

  // 选择答案并立即判断
  onOptionChange: function (e) {
    if (this.data.quizCompleted) return;
    const selectedOption = e.currentTarget.dataset.option;
    const isCorrect = selectedOption === this.data.question.correctAnswer;

    this.setData({
      selectedOption: selectedOption,
      isCorrect: isCorrect
    });

    // 根据正确或错误显示不同的提示
    if (isCorrect) {
      wx.showToast({
        title: '回答正确',
        icon: 'success'
      });
      correct_audio.play();
      // 更新分数
      this.setData({
        score: this.data.score + 10
      });
    } else {
      wx.showToast({
        title: '回答错误',
        icon: 'none'
      });
      incorrect_audio.play();
    }

    // 提交答案到数据库
    this.submitToDatabase();

    // 跳转到下一题
    setTimeout(() => {
      this.goToNextQuestion();
    }, 1500); // 等待1.5秒后跳转
  },

  // 提交答案到数据库
  submitToDatabase: function () {
    const db = wx.cloud.database();
    const answerRecord = {
      question: this.data.question.text, // 问题内容
      options: this.data.question.options, // 所有选项
      selectedOption: this.data.selectedOption, // 用户选择的答案
      correctAnswer: this.data.question.correctAnswer, // 正确答案
      isCorrect: this.data.isCorrect, // 答案是否正确
      score: this.data.score // 当前分数
    };

    db.collection('answer_record').where({
      _id: this.data.quizId // 使用传入的 ID 查找对应的记录
    }).update({
      data: {
        answers: db.command.push(answerRecord) // 将新的答题记录推入数组中
      },
      success: res => {
        console.log('答案记录更新成功');
      },
      fail: err => {
        console.error('更新答案记录失败', err);
      }
    });
  },

  // 跳转到下一题
  goToNextQuestion: function () {
    if (this.data.currentQuestionIndex < this.data.totalQuestions - 1) {
      this.setData({
        currentQuestionIndex: this.data.currentQuestionIndex + 1
      });
      this.getQuestion(this.data.currentQuestionIndex);
    } else {
      wx.showToast({
        title: '已答完所有题目',
        icon: 'success'
      });
      this.setData({
        quizCompleted: true,
        button_status:true,
      });
      this.finalizeAnswerRecord(); // 调用最终保存记录的函数
    }
  },

  // 更新最终答题记录
  finalizeAnswerRecord: function () {
    const db = wx.cloud.database();
    db.collection('answer_record').where({
      _id: this.data.quizId // 使用传入的 ID 查找对应的记录
    }).update({
      data: {
        totalScore: this.data.score, // 总分数
        totalQuestions: this.data.totalQuestions // 总题目数量
      },
      success: res => {
        console.log('最终答题记录更新成功');
      },
      fail: err => {
        console.error('更新最终答题记录失败', err);
      }
    });
  },

  toggleMusic() {
    if (this.data.isPlaying) {
      audio.pause(); // 暂停音乐
      this.setData({ isPlaying: false, rotation: 0 }); // 停止旋转
      clearInterval(this.rotationInterval); // 清除旋转的定时器
    } else {
      audio.play(); // 播放音乐
      this.setData({ isPlaying: true });
      this.startRotation(); // 开始旋转
    }
  },

  startRotation() {
    let angle = this.data.rotation; // 使用当前角度
    this.rotationInterval = setInterval(() => {
      angle += 10; // 每次增加10度
      this.setData({ rotation: angle }); // 更新旋转角度
    }, 250); 
  },

  onUnload() {
    audio.stop(); // 页面卸载时停止音乐
    clearInterval(this.rotationInterval); // 清除旋转的定时器
  }
});
